home *** CD-ROM | disk | FTP | other *** search
/ PC Graphics Unleashed / PC Graphics Unleashed.iso / ch20 / source / winlev.c < prev   
Encoding:
C/C++ Source or Header  |  1994-08-11  |  1.9 KB  |  114 lines

  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <conio.h>
  4. #include <io.h>
  5. #include <math.h>
  6.  
  7.  
  8.  
  9. #define BUFFERSIZE  128*128
  10.  
  11.  
  12. double rnd(double val);
  13.  
  14.  
  15. void main(int argc, char **argv)
  16. {
  17. int i,j,k;
  18. FILE *in, *out;
  19. int win, lev;
  20. int filesize;
  21. short inbuffer[BUFFERSIZE];
  22. unsigned char outbuffer[BUFFERSIZE];
  23. int bpf;
  24. float temp;
  25.  
  26.  
  27.   /* Ensure correct syntax */
  28.  
  29.   if(argc != 5)
  30.     {
  31.     printf("Usage:: WinLev infile outfile win lev.\n\n");
  32.     exit(1);
  33.     }
  34.  
  35.   
  36.   /* Setup input and output files */
  37.  
  38.   in = fopen(argv[1], "rb");
  39.   if(in == NULL)
  40.     {
  41.     printf("Unable to open file %s.\n\n", argv[1]);
  42.     exit(2);
  43.     }
  44.  
  45.   out = fopen(argv[2], "wb");
  46.   if(out == NULL)
  47.     {
  48.     printf("Error creating / opening file %s.\n\n", argv[2]);
  49.     exit(2);
  50.     }
  51.  
  52.   
  53.   /* Verify window and level values */
  54.  
  55.   win = atoi(argv[3]);
  56.   lev = atoi(argv[4]);
  57.  
  58.   if((win < 0) || (win > 4096))
  59.     {
  60.     printf("Window not within allowable range(1 - 4096).\n\n");
  61.     exit(3);
  62.     }
  63.  
  64.   if(((lev-win/2) < 0) || ((lev+win/2) > 4096))
  65.     {
  66.     printf("Level puts window out of range(0 - 4095).\n\n");
  67.     exit(4);
  68.     }
  69.  
  70.  
  71.   /* Calculate number of buffers per file */
  72.  
  73.   filesize = filelength( fileno(in));
  74.   bpf = filesize / sizeof(inbuffer);
  75.  
  76.  
  77.   /* Processing loop */
  78.  
  79.   for(i=0; i<bpf; i++)
  80.     {
  81.  
  82.     fread(inbuffer, sizeof(inbuffer), 1, in);
  83.  
  84.     for(j=0; j<BUFFERSIZE; j++)
  85.       {
  86.       temp = inbuffer[j] - (lev-win/2);
  87.       temp = temp*255.0/(float)win;
  88.       if(temp <= 0)
  89.         outbuffer[j] = 0;
  90.       if(temp >= 255)
  91.          outbuffer[j] = 255;
  92.         else
  93.           outbuffer[j] = (unsigned char)rnd((double)temp);
  94.       }
  95.  
  96.     fwrite(outbuffer, sizeof(outbuffer), 1, out);
  97.     }
  98.  
  99.   fclose(in);
  100.   fclose(out);
  101.  
  102. }
  103.  
  104.  
  105. double rnd(double val)
  106. {
  107. double tempval;
  108.  
  109.   tempval = floor(val);
  110.   if((val - tempval) > 0.5)
  111.     return(tempval + 1.0);
  112.    else return(tempval);
  113. }
  114.